package com.pox.guli.service.oss.controller;

import com.pox.guli.common.base.result.R;
import com.pox.guli.common.base.result.ResultCodeEnum;
import com.pox.guli.common.base.util.ExceptionUtils;
import com.pox.guli.service.base.exception.PoXException;
import com.pox.guli.service.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;

/**
 * @Author PoX21s
 * @Date: 2022/6/2 18:46
 * @Version 1.0
 */

@Api(description = "文件管理")
@RestController
@RequestMapping("/admin/oss/file")
//@CrossOrigin
@Slf4j
public class FileController {
    @Resource
    private FileService fileService;
    @Value(value = "${server.port}")
    private String port;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public R fileUpload(@ApiParam("上传的文件数据") @RequestParam("file") MultipartFile file,
                        @ApiParam("上传文件名字") @RequestParam("module") String module) {

        // 获取文件信息
        InputStream fileInputStream = null;
        try {
            fileInputStream = file.getInputStream();
        } catch (Exception e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new PoXException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }

        String originalFilename = file.getOriginalFilename();
        // 执行业务代码，上传文件到oss
        String fileUrl = fileService.upload(fileInputStream, module, originalFilename);

        // 返回结果
        return R.ok().message("文件上传成功").data("url", fileUrl);
    }

    @ApiOperation("远程调用测试")
    @GetMapping("/test")
    public R testFeign() {

        return R.ok().message("调用成功。" + port);
    }

    @ApiOperation("文件删除")
    @DeleteMapping("/remove")
    public R removeFile(@ApiParam(value = "要删除的文件路径", required = true) @RequestBody String url) {

        fileService.removeFile(url);
        return R.ok().message("文件刪除成功");
    }
}
